﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using System.Xml.Linq;
using Netkk.Common;
using Netkk.Common.Interfaces.Repositories;
using Netkk.Common.Models;

namespace Netkk.Data.Repositories
{
    public class NewsRepository : BaseRepository, INewsRepository
    {
        private string newsPath;

        protected XDocument NewsDocument
        {
            get { return CacheWrapper.Load("news", new CacheDependency(newsPath), () => XDocument.Load(newsPath)); }
        }

        public NewsRepository()
        {
            newsPath = string.Concat(ConnectionString, "News.xml");
        }

        public IEnumerable<News> Select()
        {
            IEnumerable<News> appointments = from c in NewsDocument.Element("News").Elements("Message")
                                             select getNewsFromXElement(c);
            return appointments;
        }

        private News getNewsFromXElement(XElement XNews)
        {
            return new News
            {
                Id = XNews.Element("Id").Value.ToOrDefault<Guid>(),
                Date = XNews.Element("Date").Value.ToOrDefault<DateTime>(),
                Title = XNews.Element("Title").Value,
                Teaser = XNews.Element("Teaser").Value,
                Text = XNews.Element("Text").Value
            };
        }

        public void Delete(News news)
        {
            XElement xcontent = (from c in NewsDocument.Element("News").Elements("Message")
                                 where c.Element("Id").Value.ToOrDefault<Guid>() == news.Id
                                 select c).FirstOrDefault();
            if (xcontent != null)
            {
                xcontent.Remove();
                NewsDocument.Save(newsPath);
            }
        }

        public void Save(News news)
        {
            XElement xcontent = (from c in NewsDocument.Element("News").Elements("Message")
                                 where c.Element("Id").Value.ToOrDefault<Guid>() == news.Id
                                 select c).FirstOrDefault();
            if (xcontent == null)
            {
                xcontent = new XElement("Message");
                NewsDocument.Element("News").Add(xcontent);
            }
            else
            {
                xcontent.RemoveAll();
            }

            xcontent.Add(
                new XElement("Id") { Value = news.Id.ToString("B") },
                new XElement("Date") { Value = news.Date.ToString("dd.MM.yyyy HH:mm:ss") },
                new XElement("Title") { Value = news.Title },
                new XElement("Teaser") { Value = news.Teaser },
                new XElement("Text") { Value = news.Text });

            NewsDocument.Save(newsPath);
        }

    }

}
